﻿using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.EntityFrameworkCore.Interceptors
{
    // 慢查询拦截器
    public class SlowQueryInterceptor : DbCommandInterceptor
    {
        private readonly ILogger _logger;
        private readonly TimeSpan _slowQueryThreshold = TimeSpan.FromSeconds(2);

        public SlowQueryInterceptor(ILogger logger)
        {
            _logger = logger;
        }

        public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
            DbCommand command,
            CommandEventData eventData,
            InterceptionResult<DbDataReader> result,
            CancellationToken cancellationToken = default)
        {
            var stopwatch = Stopwatch.StartNew();
            var interceptionResult = await base.ReaderExecutingAsync(
                command, eventData, result, cancellationToken);

            stopwatch.Stop();

            if (stopwatch.Elapsed > _slowQueryThreshold)
            {
                _logger.LogWarning(
                    "慢查询: {Duration}ms, SQL: {CommandText}",
                    stopwatch.ElapsedMilliseconds,
                    command.CommandText);
            }

            return interceptionResult;
        }
    }
}